//
//  ProjectsViewController.swift
//  Git@OSC
//
//  Created by AeternChan on 5/26/15.
//  Copyright (c) 2015 oschina. All rights reserved.
//

import UIKit
import ReactiveCocoa

class ProjectsViewController: UITableViewController {

    var group: ProjectGroup!
    var viewModel: ProjectsViewModel!
    var bindingHelper: TableViewBindingHelper!
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        viewModel = ProjectsViewModel(group: group)
        
        tableView.estimatedRowHeight = 44
        tableView.rowHeight = UITableViewAutomaticDimension
        
        refreshControl?.addTarget(viewModel, action: "refresh", forControlEvents: UIControlEvents.ValueChanged)
        
        bindingHelper = TableViewBindingHelper(tableView: tableView, refreshControl: refreshControl, sourceSingnal: viewModel.page.producer)
        
        viewModel.fetchProjects()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }

    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return viewModel.projects.count
    }
    
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier("ProjectCell", forIndexPath: indexPath) as! ProjectCell
        
        let project = viewModel.projects[indexPath.row]
        let projectModel = ProjectModel(project)
        
        cell.entity = projectModel
        
        return cell
    }
    
    

    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        let indexPath = tableView.indexPathForSelectedRow
        let projectVC = segue.destinationViewController as! ProjectViewController
        let project = viewModel.projects[indexPath!.row]
        let projectModel = ProjectModel(project)
        projectVC.viewModel.projectModel = projectModel
    }
    
}
